﻿using B.WMS.IWMSService.UserService;
using B.WMS.StandardReturn;
using B.WMS.WMSDtos.User;
using B.WMS.WMSEntities.User;
using MD5Hash;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Data;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;
using Volo.Abp.OpenIddict;

namespace B.WMS.User
{
    public class UserAppService : ApplicationService, IUserAppService
    {
        private readonly IRepository<UserModel, Guid> _userRepo;
        private readonly IConfiguration _config;
        public UserAppService(IRepository<UserModel, Guid> userRepo, IConfiguration config)
        {
            _userRepo = userRepo;
            _config = config;
        }
        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="userDTO"></param>
        /// <returns></returns>
        public async Task<ApiResult<UserModel>> CreateUser(UserDTO userDTO)
        {
            var result = new ApiResult<UserModel>();
            var userModel = ObjectMapper.Map<UserDTO, UserModel>(userDTO);
            userModel.Count = 3;
            userModel.Password = userModel.Password.GetMD5();
            await _userRepo.InsertAsync(userModel);
            result.Code = ApiCode.Success;
            result.ResultData = userModel;
            result.Message = "添加成功";
            return result;
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public async Task<ApiPaging<List<GetUserDTO>>> GetUsers(int pageIndex, int pageSize)
        {
            var result = new ApiPaging<List<GetUserDTO>>();
            var list = await _userRepo.GetListAsync();
            var listpage = list.OrderByDescending(x => x.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            var dto = ObjectMapper.Map<List<UserModel>, List<GetUserDTO>>(listpage);
            
            result.Code = ApiCode.Success;
            result.ResultData = dto;
            result.Message = "获取成功";
            result.TotalData = dto.Count;
            result.TotalPage = 1;
            
            return result;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="loginDTO"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<LoginDTO>> Login(string Phone, string Password)
        {
            var result = new ApiResult<LoginDTO>();
            var user = _userRepo.GetListAsync().Result.FirstOrDefault(x => x.Phone == Phone);

            //用户不存在
            if (user == null)
            {
                result.Code = ApiCode.SysError;
               result.Message = $"用户不存在,请检查手机号";
                return Task.FromResult(result);
            }
            if (user.Status == true || user.Count == 0)
            {
              
                result.Code = ApiCode.SysError;

                result.Message = $"请联系管理员，再重新登录";
                return Task.FromResult(result);
            }
            //密码错误
            var md5password = MD5Hash.Hash.GetMD5(Password);
            if (user.Count==1)
            {
                if (user.Password != md5password)
                {
                    result.Code = ApiCode.SysError;
                    user.Count=0;
                    _userRepo.UpdateAsync(user);
                    result.Message = $"登录失败,请联系管理员";
                }
            }
            if(user.Count>1)
            {
                if (user.Password != md5password)
                {
                    result.Code = ApiCode.SysError;
                    user.Count--;
                    _userRepo.UpdateAsync(user);
                    result.Message = $"登录失败,您还有{user.Count}次机会";
                }
            }
            if (user.Password == md5password)
            {
                result.Code = ApiCode.Success;
                result.Message = "登录成功";
                user.Count = 3;
                
                _userRepo.UpdateAsync(user);
                LoginDTO loginDTO = new LoginDTO();
                loginDTO.UserName = user.UserName;
                loginDTO.Phone = user.Phone;
                loginDTO.RoleName = user.RoleName;
                //loginDTO.Token = GenerateJwtToken(loginDTO);

                result.ResultData = loginDTO;
                
                return Task.FromResult(result);
            }
            return Task.FromResult(result);
        }
    //    /// <summary>
    //    /// 生成JWT令牌
    //    /// </summary>
    //    /// <param name="user"></param>
    //    /// <returns></returns>
    //    public string GenerateJwtToken(LoginDTO user)
    //    {
    //        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSettings:SecretKey"]));
    //        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

    //        var claims = new[]
    //        {
    //    new Claim("UserName", user.UserName),
    //    //new Claim("UserId", user.UserId.ToString()),
    //    new Claim("RoleName", user.RoleName.ToString()),
    //    new Claim("RoleName", user.RoleName)
    //};

    //        var token = new JwtSecurityToken(
    //            issuer: _config["JwtSettings:Issuer"],
    //            audience: _config["JwtSettings:Audience"],
    //            claims: claims,
    //            expires: DateTime.Now.AddMinutes(120),
    //            signingCredentials: credentials
    //        );

    //        return new JwtSecurityTokenHandler().WriteToken(token);
    //    }
    }
}
